package me.kennylee.tongji;

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>  ReportData接口的回调封装类 </p>
 * <p>Created on 5/11/2017.</p>
 *
 * @author kennylee
 */
public class ReportDataApiResponse<M> {
    /**
     * 原始返回的json
     */
    private final String json;
    /**
     * 转换后的实体列表。如果为空，则表示没转换或者转换失败。
     */
    private List<M> items = new ArrayList<>();

    private ReportDataApiResponse(String json, Class<? extends ReportDataItemBuilder<M>> builderClass) {
        super();
        this.json = json;
        if (builderClass != null) {
            try {
                this.items = builderClass.getConstructor(String.class).newInstance(json).build();
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
    }

    public static <T extends ReportDataItemBuilder<M>, M> ReportDataApiResponse<M> newInstance(String json, Class<T> builderClass) {
        return new ReportDataApiResponse<>(json, builderClass);
    }

    public String getJson() {
        return json;
    }

    public List<M> getItems() {
        return items;
    }

    public boolean isSuccess() {
        return isSuccess(this.json);
    }

    public static boolean isSuccess(String json) {
        JsonObject object = new Gson().fromJson(json, JsonObject.class);
        return "success".equalsIgnoreCase(object.get("header").getAsJsonObject().get("desc").getAsString());
    }
}
